package com.kk.quyan.service.impl;

import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kk.quyan.common.handler.CustomException;
import com.kk.quyan.dao.MaterialMapper;
import com.kk.quyan.entity.Label;
import com.kk.quyan.entity.Material;
import com.kk.quyan.entity.MaterialLabelRel;
import com.kk.quyan.dao.MaterialLabelRelMapper;
import com.kk.quyan.entity.request.RelRequest;
import com.kk.quyan.service.LabelService;
import com.kk.quyan.service.MaterialLabelRelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 素材标签关系表 服务实现类
 * </p>
 *
 * @author kk
 * @since 2020-11-21
 */
@Service
public class MaterialLabelRelServiceImpl extends ServiceImpl<MaterialLabelRelMapper, MaterialLabelRel> implements MaterialLabelRelService {

    @Resource
    private MaterialMapper materialMapper;
    @Resource
    private MaterialLabelRelMapper materialLabelRelMapper;
    @Resource
    private LabelService labelService;

    @Override
    public boolean saveMaterialRel(RelRequest relRequest){
        int lId = relRequest.getLId();
        //判断是否存在对应标签
        Label label = labelService.getById(lId);
        if (label==null){
            throw new CustomException(HttpStatus.HTTP_BAD_REQUEST,"标签不存在");
        }

        //判断素材是否有效
        Material material = relRequest.getMaterial();
        if (material==null){
            throw new CustomException(HttpStatus.HTTP_BAD_REQUEST,"请输入有效素材");
        }

        int mFlag = materialMapper.insert(material);
        if (mFlag==0) {
            //未插入成功
            throw new CustomException(HttpStatus.HTTP_BAD_REQUEST,"素材插入失败");
        }
        MaterialLabelRel rel=new MaterialLabelRel();
        rel.setMId(material.getId()).setLId(lId);
        int relFlag = materialLabelRelMapper.insert(rel);
        if (relFlag==0) {
            //未插入成功
            throw new CustomException(HttpStatus.HTTP_BAD_REQUEST,"关系插入失败");
        }
        return relFlag==1?true:false;
    }

    @Override
    public void saveRel(int mId, int lId) {
        //判断是否重复插入
        MaterialLabelRel materialLabelRel = materialLabelRelMapper.selectOne(new QueryWrapper<MaterialLabelRel>()
                .eq("mId", mId)
                .eq("lId", lId));
        if (materialLabelRel==null){
            materialLabelRelMapper.insert(new MaterialLabelRel().setMId(mId).setLId(lId));
        }
    }
}
